import { Fragment, cloneElement, useState } from 'react'
import { Popup, Toast, Input, DatetimePicker, PopupPosition, hooks } from 'react-vant';
import styles from './PopupDateRange.module.scss'
import { parseTime } from '@/utils';
import './index.scss'
const today = new Date()
const yesterday = new Date(today.getTime() - 24 * 60 * 60 * 1000);

// 获取最大时间间隔日期且不能超过今天
const getMaxIntervalDate = (start: string, interval: number = 180) => {
    const startDate = new Date(start)
    const maxDate = new Date(startDate.setDate(startDate.getDate() + interval))
    // const now = new Date()

    if (maxDate > yesterday) {
        return yesterday
    }
    return maxDate
}

// 判断结束时间是否在开始日期后推的interval天内
const isDateInRange = (dateToCheck: string, startDate: string, endDate: string) => {
    const date1 = new Date(dateToCheck);
    const date2 = new Date(startDate);
    const date3 = new Date(endDate);

    return date1 >= date2 && date1 <= date3;
}

const PopupDateRange: React.FC<any> = (props) => {

    const { onConfirm, children } = props

    const [state, setState] = useState<PopupPosition>('')

    const onClose = () => setState('')

    const [dateTime, setDateTime] = useState(new Date())

    const [activeDateType, setActiveDateType] = useState(0)

    const [dateRange, updateDateRange] = hooks.useSetState({
        start: parseTime(yesterday, '{y}-{m}-{d}'),
        end: parseTime(yesterday, '{y}-{m}-{d}'),
    })

    let [minDate, setMinDate] = useState(new Date("2023-01-01"))

    let [maxDate, setMaxDate] = useState(yesterday)
    // 日期类型切换
    const activeDateTypeChange = (type: number) => {
        if (type === 0) {
            setMaxDate(new Date())
        }
        if (type === 1 && !dateRange.start) {
            return Toast.info('请先选择开始日期')

        } else if (type === 1 && dateRange.start) {
            // 清空结束日期
            const maxEndDate = getMaxIntervalDate(dateRange.start)

            setMaxDate(maxEndDate)
            if (!isDateInRange(dateRange.end, dateRange.start, parseTime(maxEndDate, '{y}-{m}-{d}'))) {
                updateDateRange(dateRange => ({ ...dateRange, end: parseTime(maxEndDate, '{y}-{m}-{d}') }))
            }
        }

        setActiveDateType(type)
        setDateTime(type === 0 ? new Date(dateRange.start) : new Date(dateRange.end))
        setMinDate(type === 0 ? new Date("2023-01-01") : new Date(dateRange.start))
    }

    // 日期选择
    const dateTimeChange = (val: any) => {
        if (activeDateType === 0) {
            const startDateStr = parseTime(val, '{y}-{m}-{d}')
            const maxEndDate = getMaxIntervalDate(startDateStr)
            if (!isDateInRange(dateRange.end, startDateStr, parseTime(maxEndDate, '{y}-{m}-{d}'))) {
                return updateDateRange({ start: startDateStr, end: parseTime(maxEndDate, '{y}-{m}-{d}') })
            }
            updateDateRange({ start: startDateStr })
        }
        if (activeDateType === 1) {
            updateDateRange({ end: parseTime(val, '{y}-{m}-{d}') })
        }
        setDateTime(val)
    }

    // 确认按钮
    const confirm = () => {
        if (!dateRange.start || !dateRange.end) {
            return Toast.info('请选择日期范围')
        }
        setState('')

        onConfirm([dateRange.start, dateRange.end])
    }
    return (
        <Fragment>
            {children && cloneElement(children, { onClick: () => setState('bottom') })}
            <Popup round
                visible={state === 'bottom'}
                position='bottom'
                onClose={onClose}>
                <div className={styles['content-block']} >
                    <div className={styles['content-head']}>
                        <span className={styles['cancel-btn']} onClick={() => onClose()}>取消</span>
                        {/* <span className={styles['tit']}>确定</span> */}
                        <span className={styles['confirm-btn']} onClick={() => confirm()}>确定</span>
                    </div>
                    <div className={styles['date-range-block']}>
                        <div
                            style={({ "--rv-input-text-color": activeDateType === 0 ? '#417CE8' : '#323232' } as React.CSSProperties)}
                            className={`${styles['date-block']} ${activeDateType === 0 ? styles['date-active'] : ''}`}
                            onClick={() => activeDateTypeChange(0)}
                        >
                            <Input readOnly value={dateRange.start} align="center" placeholder='开始日期'></Input>
                        </div>
                        <span className={styles['connec-syb-block']}>至</span>
                        <div
                            style={({ "--rv-input-text-color": activeDateType === 1 ? '#417CE8' : '#323232' } as React.CSSProperties)}
                            className={`${styles['date-block']} ${activeDateType === 1 ? styles['date-active'] : ''}`}
                            onClick={() => activeDateTypeChange(1)}>
                            <Input readOnly value={dateRange.end} align="center" placeholder='结束日期'></Input>
                        </div>
                    </div>
                    <div className={styles['range-picker-block']}>
                        <DatetimePicker
                            showToolbar={false}
                            title='选择年月日'
                            type='date'
                            minDate={minDate}
                            maxDate={maxDate}
                            value={dateTime}
                            onChange={dateTimeChange}
                        />
                    </div>
                </div>
            </Popup>
        </Fragment>
    )
}

export default PopupDateRange